<template>
  <view>
    <view class="aaa">
      <view class="tuan_title">
        <input
          v-model="tuanTitle"
          placeholder="请输入标题"
          maxlength="100"
          ref="titleInput"
          @input="adjustHeight('titleInput')"
        />
      </view>
      <!-- 添加灰色间隔线 -->
      <view class="line"></view>
      <view class="tuan_details">
        <textarea
          v-model="tuanDetail"
          placeholder="请输入组团详情"
          maxlength="5000"
          ref="detailInput"
          auto-height
          @input="adjustHeight('detailInput')"
        ></textarea>
      </view>
      <!-- 显示上传的图片 -->
      <view class="imageContainer">
        <view
          v-for="(image, index) in images"
          :key="index"
          class="imageWrapper"
        >
          <image :src="image" class="theImage"></image>
          <!-- 叉叉删除按钮 -->
          <button class="deleteImageButton" @click="deleteImage(index)">
            <image src="/static/my-icons/deleteImage.png" mode="'aspectFit'" />
          </button>
        </view>
        <!-- 上传图片 -->
        <button class="uploadButton" @click="uploadImage">
          <image src="/static/my-icons/uploadImage.png"></image>
        </button>
      </view>

      <!-- 添加灰色间隔线 -->
      <view class="line"></view>
      <view class="tagsContainer">
        <view class="tags" v-for="(tag, index) in tagName" :key="index"
          >{{ tag }}
          <!-- 叉叉删除按钮 -->
          <button class="deleteTagButton" @click="deleteTag(index)">
            <image src="/static/my-icons/deleteTag.png" mode="'aspectFit'" />
          </button>
        </view>
        <view class="tagButton1">
          <button class="select-tags" @click="showTagPopup">+选择标签</button>
        </view>
        <view class="tagButton2">
          <button class="tagButton" @click="showPopup">+自定义标签</button>
        </view>
      </view>
      <view class="numberContainer">
        <text>需要人数：</text>
        <input
          class="numberInput"
          type="number"
          v-model="requiredPeople"
          placeholder="  "
        />
        <text>人</text>
      </view>
      <view class="auto-end">
        <text>达到组团需要人数时自动结束组团：</text>
        <switch :checked="autoEnd" @change="autoEndChange" />
        <text>{{ autoEnd ? "是" : "否" }}</text>
      </view>
      <view class="agreeOption">
        <text>加入该组团需要经过你的问题验证：</text>
        <switch :checked="needAgree" @change="agreeChange" />
        <text>{{ needAgree ? "是" : "否" }}</text>
      </view>
      <view v-if="needAgree === true" class="theQuestion">
        <textarea
          v-model="question"
          placeholder="请输入问题"
          maxlength="150"
          ref="questionInput"
          auto-height
          @input="adjustHeight('questionInput')"
        ></textarea>
      </view>
      <!-- 新增开始时间选择 -->
      <uni-forms-item label="开始时间"  name="beginTime">
        <uni-datetime-picker v-model="beginTime" type="datetime"/>
      </uni-forms-item>
   
      <!-- 新增结束时间选择 -->
      <uni-forms-item label="结束时间"  name="endTime">
        <uni-datetime-picker v-model="endTime" type="datetime" />
      </uni-forms-item>
      <uni-forms-item label="组团地点" name="location">
        <view class="locate">
          <text class="tx">{{location}}</text>
          <uni-icons type="location" size="30" class="icon" @click="requireLocate"></uni-icons>
        </view>
      </uni-forms-item>
      <!-- 弹出框 -->
      <uni-popup ref="popup" type="dialog">
        <uni-popup-dialog
          type="info"
          title="自定义标签"
          content="请输入标签"
          :before-close="true"
          @confirm="confirmTags()"
          @close="cancelTags"
        >
          <input
            class="tagInput"
            v-model="tagInputs"
            placeholder="请输入标签"
          />
        </uni-popup-dialog>
      </uni-popup>
    </view>
    <view class="twoButton">
      <view class="saveButton" @click="saveDraft">暂存</view>
      <view class="sendButton" @click="publish">发布</view>
    </view>
    <!-- 标签选择弹出框 -->
    <uni-popup ref="tagPopup" type="dialog">
      <uni-popup-dialog
        type="info"
        title="热门标签"
        @confirm="confirmHotTags"
        @close="cancelHotTags"
      >
        <view class="hot-tags-container">
          <view
            v-for="(tag, index) in hotTags"
            :key="index"
            class="hot-tags"
            :class="{ selected: selectedTags.includes(tag) }"
            @click="selectTag(tag)"
          >
            {{ tag }}
          </view>
        </view>
      </uni-popup-dialog>
    </uni-popup>
  </view>
</template>

<script>
export default {
  data() {
    return {
      tuanTitle: "",
      tuanDetail: "",
      images: [],
      tagName: [],
      tagInputs: "", // 用于存储输入的标签内容
      requiredPeople: "",
      needAgree: false,
      hotTags: [], // 用于存储从后端获取的标签
      selectedTags: [], // 用于存储用户选中的标签
      question: "", // 申请加入的提问验证
      autoEnd: false,
      beginTime: "",
      endTime: "",
      location: "",
      longitude: "",
      latitude: "",
    };
  },
  methods: {
    //选择地点
    requireLocate() {
        uni.chooseLocation({
          success: (res) => {
            this.location = res.address;
            this.latitude = res.latitude;
            this.longitude = res.longitude;
          }
        });
      },
    uploadImage() {
      // 选择图片
      uni.chooseImage({
        count: 9, // 修改: 将图片最大上传数量改为9
        sizeType: ["original", "compressed"], // 可以指定是原图还是压缩图，默认二者都有
        sourceType: ["album", "camera"], // 可以指定来源是相册还是相机，默认二者都有
        success: (chooseImageRes) => {
          const tempFilePaths = chooseImageRes.tempFilePaths;
          // 上传图片
          tempFilePaths.forEach((filePath, index) => {
            if (this.images.length < 9) {
              // 确保最多存储9张图片
              uni.uploadFile({
                url: "http://localhost:8000/upload", // 后端接口路径
                filePath: filePath,
                name: "file",
                formData: {
                  user: "test",
                },
                success: (uploadRes) => {
                  console.log("上传成功", uploadRes.data);
                  // 解析服务器返回的 JSON 数据，提取图片路径
                  const responseData = JSON.parse(uploadRes.data);
                  if (responseData.code === 200) {
                    this.images.push(responseData.data);
                  } else {
                    console.error("上传失败", responseData);
                  }
                },
                fail: (err) => {
                  console.error("上传失败", err);
                },
              });
            }
          });
        },
      });
    },

    // 获取热门标签列表
    async fetchTags() {
      try {
        const res = await uni.$http.get("/tag/getHotTags"); // 请求后端获取标签数据
        if (res.data && res.data.data) {
          console.log("获取热门标签成功", res.data);
          this.hotTags = res.data.data.slice(0, 20); 
        } else {
          console.error("获取标签失败");
        }
      } catch (error) {
        console.error("请求标签失败", error);
      }
    },

    // 点击选择标签时弹出选择框
    showTagPopup() {
      this.fetchTags(); // 获取标签数据
      this.$refs.tagPopup.open(); // 打开弹出框
    },

    deleteTag(index) {
      this.tagName.splice(index, 1); // 删除对应索引的标签
    },

    selectTag(tag) {
      if (this.selectedTags.includes(tag)) {
        this.selectedTags = this.selectedTags.filter((t) => t !== tag);
      } else {
        this.selectedTags.push(tag);
      }
    },

    // 点击自定义标签时弹出选择框
    showPopup() {
      this.tagInputs = "";
      this.$refs.popup.open(); // 打开弹出框
    },

    confirmTags() {
      if (this.tagInputs.trim()) {
        this.tagName = [...new Set([...this.tagName, this.tagInputs.trim()])]; // 合并已选标签和自定义标签
      }
      this.$refs.popup.close();
    },
    cancelTags() {
      this.$refs.popup.close();
    },

    confirmHotTags() {
      this.tagName = [...new Set([...this.tagName, ...this.selectedTags])]; // 合并已选标签和自定义标签
      this.selectedTags = []; // 清空选中标签
      this.$refs.tagPopup.close();
    },
    cancelHotTags() {
      this.$refs.tagPopup.close();
    },

    agreeChange(e) {
      this.needAgree = e.detail.value; // 修改: 直接赋值 e.detail.value
    },

    autoEndChange(e) {
      this.autoEnd = e.detail.value;
    },

    //保存草稿
    saveDraft() {
      if (this.tuanTitle.trim() === "" || this.tuanDetail.trim() === "") {
        uni.showToast({
          title: "组团标题和组团详情不能为空！",
          icon: "none",
          duration: 2000,
        });
      } else {
        uni.showModal({
          title: "",
          content: "是否暂存该组团信息？",
          success: (res) => {
            if (res.confirm) {
              // 构建tuan对象
              const tuan = {
                tuanTitle: this.tuanTitle,
                tuanDetail: this.tuanDetail,
                requiredPeople: this.requiredPeople,
                autoEnd: this.autoEnd,
                needAgree: this.needAgree,
                question: this.question,
                beginTime: this.beginTime,
                endTime: this.endTime,
                location: this.location,
                longitude: this.longitude,
                latitude: this.latitude,
              };

              //  构建tuanDto对象
              const tuanDto = {
                tuan: tuan,
                images: this.images,
                tagName: this.tagName,
              };

              //  打印tuanDto对象以进行调试
              console.log("tuanDto:", tuanDto);

              uni.$http
                .post("/tuan/saveDraft", tuanDto)
                .then((res) => {
                  console.log("暂存操作", res.data);
                  // 解析服务器返回的 JSON 数据
                  const responseData = res.data;
                  if (responseData.code === 200) {
                    // 使用 uni.showToast 提示用户
                    uni.showToast({
                      title: "暂存成功",
                      icon: "success",
                      duration: 2000,
                    });

                    //清除页面数据
                    this.tuanTitle = "";
                    this.tuanDetail = "";
                    this.images = [];
                    this.tagName = [];
                    this.tagInputs = "";
                    this.requiredPeople = "";
                    this.autoEnd = false;
                    this.needAgree = false;
                    this.question = "";
                    this.beginTime = "";
                    this.endTime = "";
                    this.location = "";
                    this.longitude = "";
                    this.latitude = "";
                  } else {
                    console.log("暂存失败", responseData);
                    uni.showToast({
                      title: "暂存失败",
                      icon: "none",
                      duration: 2000,
                    });
                  }
                })
                .catch((err) => {
                  console.error("暂存失败", err);
                  uni.showToast({
                    title: "暂存失败",
                    icon: "none",
                    duration: 2000,
                  });
                });
            } else if (res.cancel) {
              console.log("用户取消了暂存操作");
            }
          },
        });
      }
    },

    //发布组团
    publish() {
      if (this.tuanTitle.trim() === "" || this.tuanDetail.trim() === "") {
        uni.showToast({
          title: "组团标题和组团详情不能为空！",
          icon: "none",
          duration: 2000,
        });
      } else {
        uni.showModal({
          title: "",
          content: "是否发布该组团信息？",
          success: (res) => {
            if (res.confirm) {
              // 构建tuan对象
              const tuan = {
                tuanTitle: this.tuanTitle,
                tuanDetail: this.tuanDetail,
                requiredPeople: this.requiredPeople,
                autoEnd: this.autoEnd,
                needAgree: this.needAgree, // 新增：添加 needAgree 到 tuan 对象
                question: this.question,
                beginTime: this.beginTime,
                endTime: this.endTime,
                location: this.location,
                longitude: this.longitude,
                latitude: this.latitude,
              };

              //  构建tuanDto对象
              const tuanDto = {
                tuan: tuan,
                images: this.images,
                tagName: this.tagName,
              };

              //  打印tuanDto对象以进行调试
              console.log("tuanDto:", tuanDto);

              uni.$http
                .post("/tuan/sendTuan", tuanDto)
                .then((res) => {
                  console.log("发布操作", res.data);
                  // 解析服务器返回的 JSON 数据
                  const responseData = res.data;
                  if (responseData.code === 200) {
                    // 使用 uni.showToast 提示用户
                    uni.showToast({
                      title: "发布成功",
                      icon: "success",
                      duration: 2000,
                    });

                    //清除页面数据
                    this.tuanTitle = "";
                    this.tuanDetail = "";
                    this.images = [];
                    this.tagName = [];
                    this.tagInputs = "";
                    this.requiredPeople = "";
                    this.autoEnd = false;
                    this.needAgree = false;
                    this.question = "";
                    this.beginTime = "";
                    this.endTime = "";
                    this.location = "";
                    this.longitude = "";
                    this.latitude = "";
                  } else {
                    console.log("发布失败", responseData);
                    uni.showToast({
                      title: "发布失败",
                      icon: "none",
                      duration: 2000,
                    });
                  }
                })
                .catch((err) => {
                  console.error("发布失败", err);
                  uni.showToast({
                    title: "发布失败",
                    icon: "none",
                    duration: 2000,
                  });
                });
            } else if (res.cancel) {
              console.log("用户取消了发布操作");
            }
          },
        });
      }
    },
    adjustHeight(refName) {
      this.$nextTick(() => {
        const element = this.$refs[refName];
        if (element) {
          element.style.height = "auto"; // 先重置高度
          element.style.height = element.scrollHeight + "px"; // 重新调整高度
        }
      });
    },
    deleteImage(index) {
      this.images.splice(index, 1); // 删除对应索引的图片
    },
  },
};
</script>

<style lang="scss">
page {
  background-color: white;
  padding-bottom: 60px;
}

.tagButton1 {
  display: flex;
  background: none;
  width: auto;
  gap: 5px;
}

.tagButton2 {
  display: flex;
  background: none;
  width: auto;
  gap: 5px;
}

.twoButton {
  height: 47px;
  z-index: 10;
  position: fixed;
  bottom: 0;
  width: 100%;
  box-shadow: 0 -2px 10px rgba(0, 0, 0, 0.171);
  display: flex;
  justify-content: space-around;
  align-items: stretch; /* 确保子元素高度占满父容器 */
}

.saveButton {
  background-color: #d2d2d2;
  flex: 1;
  height: 100%;
  font-size: 18px;
  text-align: center;
  padding-top: 12px;
}

.sendButton {
  flex: 1;
  height: 100%;
  background-color: #fbd269;
  font-size: 18px;
  text-align: center;
  padding-top: 12px;
}

.tagsContainer {
  display: flex;
  flex-wrap: wrap; /* 允许换行 */
  gap: 5px;
}

.select-tags {
  height: 30px;
  background-color: #f1f1f1;
  margin-left: 0;
  font-size: 16px;
  border-radius: 20px;
  display: flex; /* 新增: 使用 flex 布局 */
  align-items: center; /* 新增: 垂直居中 */
  justify-content: center; /* 新增: 水平居中 */
  padding: 0 10px; /* 新增: 添加左右内边距 */
}

.tagButton {
  height: 30px;
  background-color: #f1f1f1;
  margin-left: 0;
  font-size: 16px;
  border-radius: 20px;
  display: flex; /* 新增: 使用 flex 布局 */
  align-items: center; /* 新增: 垂直居中 */
  justify-content: center; /* 新增: 水平居中 */
  padding: 0 10px; /* 新增: 添加左右内边距 */
}

.tags {
  height: 30px;
  background-color: #fbd269;
  color: white;
  margin-left: 0;
  font-size: 16px;
  border-radius: 20px;
  display: flex; /* 新增: 使用 flex 布局 */
  align-items: center; /* 新增: 垂直居中 */
  justify-content: center; /* 新增: 水平居中 */
  padding: 0 10px; /* 新增: 添加左右内边距 */
}

.tagInput {
  width: auto;
  border-radius: 5px;
  padding: 5px 5px;
  background-color: rgb(255, 255, 255);
  border: 1px solid rgb(179, 175, 175);
}

.hot-tags-container {
  display: flex;
  flex-wrap: wrap;
  gap: 5px;
}

.hot-tags {
  height: 30px;
  background-color: #f1f1f1;
  color: rgb(107, 107, 107);
  margin-left: 0;
  font-size: 16px;
  border-radius: 20px;
  display: flex; /* 新增: 使用 flex 布局 */
  align-items: center; /* 新增: 垂直居中 */
  justify-content: center; /* 新增: 水平居中 */
  padding: 0 10px; /* 新增: 添加左右内边距 */
  &.selected {
    background-color: #fbd269; // 选中标签背景颜色变为黄色
  }
}

.numberContainer {
  display: flex;
  padding-top: 8px;
}

.numberInput {
  width: 150rpx;
  margin-right: 15rpx;
  border-radius: 5px;
  padding-left: 5px;
  background-color: rgb(255, 255, 255);
  border: 1px solid rgb(179, 175, 175);
}

.agreeOption {
  margin-top: 5px;
  margin-bottom: 5px;
}
.auto-end {
  margin-top: 5px;
}

.tuan_title input {
  height: 100%;
  width: 100%;
  font-weight: bold;
  font-size: 17px;
}

.tuan_details textarea {
  min-height: 200px;
  max-height: 400px;
  height: 100%;
  width: 100%;
}

.tuan_title {
  margin-top: 8px;
  height: auto;
  font-size: 17px;
}

.tuan_details {
  min-height: 200px;
  height: auto;
}

.line {
  border-top: 1px solid rgb(213, 213, 213);
  margin: 10px 0px;
}

.aaa {
  margin-left: 5px;
  margin-right: 5px;
  margin-top: 5px;
}

.uploadButton {
  padding: 0; /* 移除按钮的内边距 */
  border: none; /* 移除按钮的边框 */
  display: grid;
  place-items: center; /* 水平和垂直居中 */
  width: 29vw;
  height: 29vw;
  margin-left: 0;
  border-radius: 10px;

  image {
    display: block; /* 使图片表现为块级元素 */
    width: 80%; /* 图片宽度撑满按钮 */
    height: 80%; /* 图片高度撑满按钮 */
    object-fit: cover; /* 保持图片比例并覆盖整个按钮 */
  }
}

.imageContainer {
  display: flex;
  margin-top: 10px;
  flex-wrap: wrap; /* 允许换行 */
  gap: 1vw;
}

.imageWrapper {
  position: relative;
  display: inline-block;
}

.theImage {
  width: 29vw;
  height: 29vw;
  border-radius: 10px;
  object-fit: cover; /* 确保图片保持比例 */
}

.deleteTagButton {
  padding: 0; /* 移除按钮的内边距 */
  border: none; /* 移除按钮的边框 */
  display: grid;
  place-items: center; /* 水平和垂直居中 */
  width: 20px;
  height: 20px;
  margin-left: 3px;
  background: none;
  border-radius: 50%;

  image {
    display: block; /* 使图片表现为块级元素 */
    width: 100%; /* 图片宽度撑满按钮 */
    height: 100%; /* 图片高度撑满按钮 */
    object-fit: cover; /* 保持图片比例并覆盖整个按钮 */
  }
}

.deleteImageButton {
  padding: 0; /* 移除按钮的内边距 */
  border: none; /* 移除按钮的边框 */
  display: grid;
  place-items: center; /* 水平和垂直居中 */
  width: 20px;
  height: 20px;
  margin-left: 0;
  position: absolute;
  top: 5px;
  right: 5px;
  background: none;
  border-radius: 50%;

  image {
    display: block; /* 使图片表现为块级元素 */
    width: 100%; /* 图片宽度撑满按钮 */
    height: 100%; /* 图片高度撑满按钮 */
    object-fit: cover; /* 保持图片比例并覆盖整个按钮 */
    opacity: 0.7;
  }
}

.theQuestion {
  width: 90vw;
  border-radius: 5px;
  min-height: 25px;
  padding: 5px 5px;
  background-color: rgb(255, 255, 255);
  border: 1px solid rgb(179, 175, 175);
  align-items: center;
  justify-content: center;
  margin-bottom: 5px;

  textarea {
    width: 100%;
  }
}

.locate {
      display: flex;
      height: 35px;
      flex: 1;
      text-align: center;
      border: 1px solid #e6e6e6;

      .icon {
        text-align: right;
        padding-right: 10rpx;
      }

      .tx {
        width: 100%;
        height: 100%;
        padding-left: 5px;
        display: flex;
        align-items: center;
      }
    }

</style>